import axios from "axios";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { serverUrl, getToken } from "./tools";

//创建一个axios实例 用来发送网络请求

const instance = axios.create({
  baseURL: serverUrl, //baseURL是基础地址，可以进行拼接使用
  timeout: 5000,
});

// 网络请求拦截器
// Add a request interceptor
// 发起请求时的拦截器
instance.interceptors.request.use(
  // 请求成功的回调
  function(config) {
    // Do something before request is sent
    NProgress.start(); //显示进度条
    config.headers.token = getToken();
    return config;
  },
  // 请求失败的回调
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
instance.interceptors.response.use(
  function(response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    NProgress.done(); //隐藏进度条
    return response.data;
  },
  function(error) {
    console.dir(error);
    if (error.response.status == 401) {
      window.location.href = "http://localhost:8080/#/login";
    }
    NProgress.done(); //隐藏进度条
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);

/**
 * get请求
 * @params {*} url 请求地址
 * @params {*} param 请求配置
 * @returns
 */
export const get = (url, params) => instance.get(url, { params });
/**
 * post请求
 * @param {*} url 请求地址
 * @param {*} data 数据
 * @returns
 */
export const post = (url, data) => instance.post(url, data);
/**
 *put修改
 * @param {*} url 请求地址
 * @param {*} data 数据
 * @returns
 */
export const put = (url, data) => instance.put(url, data);
/**
 *del删除
 * @param {*} url 请求地址 ？？？为什么不带数据过去？？？
 * @returns
 */
export const del = (url) => instance.delete(url);
